#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime

import contextlib

from v8.engine import db_conn
from v8.model.user import User, Contacts
from v8.engine.util import model_to_dict


def get_user_info(name):
    """Get user info by name.

    Args:
        name (string): user's email address

    Returns:
        dict of user info or None.
    """
    with contextlib.closing(db_conn.gen_session_class('base')()) as session:
        _user = session.query(User) \
                       .filter(User.deleted == 0,
                               User.name == name) \
                       .first()
        if not _user:
            return None
        else:
            return model_to_dict(_user)


def add_user(user_info):
    """Add user.

    Args:
        user_info (dict): user info.

    Returns:
        dict of user info or None when user_name is exist.
    """
    with contextlib.closing(db_conn.gen_session_class('base')()) as session:
        _user = session.query(User) \
                       .filter(User.name == user_info['name']) \
                       .first()
        if _user is not None:
            return None

        _user = User()
        _user.name = user_info['name']
        _user.password = user_info['password']
        _user.phone = user_info['phone']
        _user.logo = user_info['logo']
        _user.nickname = user_info['nickname']
        _user.deleted = 0
        _user.create_time = \
            datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        _user.update_time = _user.create_time
        session.add(_user)
        session.commit()
        return model_to_dict(_user)


def get_user_contacts(user_name):
    """Get user contacts by user_name.

    Args:
        user_name (string):

    Returns:
        dict of user info or None.
    """
    with contextlib.closing(db_conn.gen_session_class('base')()) as session:
        _user = session.query(User) \
                       .filter(User.name == user_name, User.deleted == 0) \
                       .first()
        if _user is None:
            return None

        _contacts = session.query(Contacts) \
                           .filter(Contacts.user_id == _user.id) \
                           .first()

        if not _contacts:
            return None
        else:
            # 1|doubi,2|MM
            contact_infos = {}
            contacts_str = model_to_dict(_contacts)['contacts']
            contacts = contacts_str.split(',')
            for contact in contacts:
                if contact and '|' in contact:
                    contact_info = contact.split('|')
                    contact_infos[int(contact_info[0])] = contact_info[1]
            contacts_ids = contact_infos.keys()

            ret = []
            for _user in session.query(User).filter(User.id.in_(contacts_ids),
                                                    User.deleted == 0):
                _user_info = {}
                _user_info['user_id'] = _user.id
                _user_info['name'] = _user.name
                _user_info['logo'] = _user.logo
                _user_info['nickname'] = _user.nickname
                _user_info['aliasname'] = contact_infos[_user.id]
                ret.append(_user_info)
            return ret


def update_user_contacts(user_id, contacts):
    """Update user contacts.

    Args:
        user_id (int):
        contacts (string): the contend of contacts

    Returns:
        dict of user's contacts.
    """
    with contextlib.closing(db_conn.gen_session_class('base')()) as session:
        _contacts = session.query(Contacts) \
                       .filter(Contacts.user_id == user_id) \
                       .first()
        if not _contacts:
            _contacts = Contacts()
            _contacts.user_id = user_id
            _contacts.contacts = contacts
            _contacts.create_time = \
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            _contacts.update_time = _contacts.create_time
        else:
            _contacts.contacts = contacts
            _contacts.update_time = \
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        session.add(_contacts)
        session.commit()
        return model_to_dict(_contacts)
